<template>
    <div>
        <top-bar></top-bar>
        <left-bar :datas='data'></left-bar>
        <div class="main">
            <div class="main-mains">
                <div class="main-content">
                    <div class="main-mains-top">
                        编辑有积分资讯文章
                        <el-button size="mini" type="primary" @click="goBack" class="goBack">返回</el-button>
                    </div>
                    <div class="topEdit">
                        <li>
                            <span>浏览发放总积分：</span>
                            <el-input placeholder="" v-model.trim="read_budget"></el-input>
                        </li>
                        <li>
                            <span>浏览每人可得积分：</span>
                            <el-input placeholder="" v-model.trim="read_score"></el-input>
                        </li>
                    </div>
                    <div class="editItem">
                        <div class="group1 clear">
                            <span class="leftTitle">*所属项目</span>
                            <div class="rightContent">
                                <el-select v-model="projectId" :disabled="urlType == 'againEdit'" placeholder="请选择">
                                    <el-option v-for="item in projectOptions" :key="item.value" :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </div>
                        </div>
                    </div>
                    <div class="editItem">
                        <div class="group1 clear">
                            <span class="leftTitle">*资讯标题</span>
                            <div class="rightContent lgRightContent">
                                <el-input placeholder="" v-model.trim="articleTitle"></el-input>
                            </div>
                        </div>
                    </div>
                    <div class="editItem">
                        <div class="group1 clear">
                            <span class="leftTitle">*分类</span>
                            <div class="rightContent">
                                <el-select v-model="category_id" placeholder="请选择">
                                    <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </div>
                        </div>
                    </div>
                    <div class="editItem">
                        <div class="group1 clear">
                            <span class="leftTitle">*作者</span>
                            <div class="rightContent lgRightContent">
                                <el-input placeholder="" v-model.trim="article_source"></el-input>
                            </div>
                        </div>
                    </div>
                    <div class="editItem">
                        <div class="group1 clear">
                            <span class="leftTitle">文章封面</span>
                            <div class="rightContent">
                                <el-upload :action="uploadImgUrl" :on-success="uploadImgSuccess" list-type="picture-card" :data="uploadData" name="img" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :file-list="img_url" :headers="uploadHeader">
                                    <i class="el-icon-plus"></i>
                                </el-upload>
                            </div>
                        </div>
                    </div>
                    <div class="editItem">
                        <div class="group1 clear">
                            <span class="leftTitle">*文章内容</span>
                            <div class="rightContent lgRightContent">
                                <script id="productDescriptionContainer" name="productDescriptionContainer" type="text/plain">
                                    这里写你的初始化内容
                                </script>
                            </div>
                        </div>
                    </div>
                    <div class="operationButtom">
                        <el-button round size="medium" @click="goBack">取消</el-button>
                        <el-button round size="medium" v-if="urlType == 'add'" type="warning" @click="saveArticle(2)">存为草稿</el-button>
                        <el-button round size="medium" v-if="urlType == 'againEdit'" type="danger" @click="saveArticle(0)">下架</el-button>
                        <el-button round size="medium" type="success" @click="saveArticle(1)">发布</el-button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>


<script>
import leftBar from "@/components/leftBar";
import topBar from "@/components/topBar";
import pointsNews from "@/api/pointsNews";
import medical from "@/api/medical";
import store from "../store";
import pubilc from "@/api/pubilc";
export default {
  components: {
    leftBar,
    topBar
  },
  data() {
    return {
      data: "newsman",
      newImgUrl: [],
      img_url: [],
      uploadImgUrl: "http://dev.cso.miotchina.net/adm/upload",
      projectId: "",
      projectOptions: [],
      category_id: "",
      categoryOptions: [],
      uploadData: {
        type: 11,
        filename: "img"
      },
      uploadHeader: {
        Authorization: "Bearer " + store.state.access_token
      },
      read_score: "",
      read_budget: "",
      articleTitle: "",
      article_source: "",
      urlType: "",
      urlArticleId: ""
    };
  },
  mounted() {
    this.urlType = this.getUrlKey("type");
    this.urlArticleId = this.getUrlKey("articleId");
    if (this.urlType == "againEdit") {
      this.getArticleDetail(this.urlArticleId);
    }
    UE.delEditor("productDescriptionContainer");
    this.ueditorFun(); //初始化编辑器
    this.getCategory();
    this.getProject();
  },
  methods: {
    //编辑器函数
    ueditorFun() {
      var _this = this;
      // 产品描述编辑器
      _this.productDescriptionue = UE.getEditor("productDescriptionContainer", {
        initialFrameWidth: 950,
        initialFrameHeight: 500,
        autoHeightEnabled: false,
        zIndex: 0,
        maximumWords: 10000, //允许的最大字符数
        saveInterval: 999999 //自动保存间隔时间，单位ms
      });
      _this.productDescriptionue.ready(function() {
        _this.productDescriptionue.setContent(_this.productDescHtml);
      });
    },
    //获取文章详情
    getArticleDetail(id) {
      let _this = this;
      let options;
      options = {
        article_id: id
      };
      pointsNews.getPointsNewDetail(options).then(function(res) {
        let data = res.data;
        if (res.code == 1) {
          let img_url = [];
          _this.category_id = data.categorys.id;
          _this.projectId = data.spid;
          _this.productDescHtml = data.content;
          _this.ueditorFun();
          _this.articleTitle = data.title;
          _this.article_source = data.article_source;
          _this.read_score = data.read_score;
          _this.read_budget = data.read_budget;
          if (data.img_url.length > 0) {
            for (let i = 0; i < data.img_url.length; i++) {
              let imgeSplit = data.img_url[i].split("/");
              let imgName = imgeSplit[imgeSplit.length - 1];
              img_url.push({
                name: imgName,
                url: data.img_url[i]
              });
            }
          }
          _this.img_url = img_url;
          _this.newImgUrl = img_url;
        }
      });
    },
    //保存文章
    saveArticle(type) {
      let _this = this;
      let options;
      let img_url = [];
      this.productDescHtml = this.productDescriptionue.getContent();
      if (
        this.articleTitle === "" ||
        this.productDescHtml === "" ||
        this.projectId === "" ||
        this.category_id === "" ||
        this.newImgUrl.length <= 0 ||
        this.article_source === ""
      ) {
        this.messageAlert("请填写完整信息");
        return;
      }
      if (this.read_budget < this.read_score) {
        this.messageAlert("总发放积分不能小于每人浏览得到的积分！");
        return;
      }
      for (let i = 0; i < this.newImgUrl.length; i++) {
        if (this.newImgUrl[i].url.indexOf("blob:") != -1) {
          img_url.push(this.newImgUrl[i].response.data.file.path);
        } else {
          img_url.push(this.newImgUrl[i].name);
        }
      }
      img_url = JSON.stringify(img_url);
      options = {
        check_status: type,
        title: this.articleTitle,
        content: this.productDescHtml,
        category_id: this.category_id,
        weights: this.weights,
        author: this.article_source,
        img_url: img_url,
        read_score: this.read_score,
        read_budget: this.read_budget
      };
      if (this.urlType == "againEdit") {
        // 编辑资讯:
        options = Object.assign(options, { article_id: this.urlArticleId });
      } else if (this.urlType == "add") {
        // 新增资讯
        options = Object.assign(options, { spid: this.projectId });
      }
      pointsNews.saveArticle(options, this.urlType).then(function(res) {
        let data = res.data;
        if (res.code == 1) {
          _this.successfulAlert("操作成功");
          history.go(-1);
        }
      });
    },
    //获取分类
    getCategory() {
      let _this = this;
      this.categoryOptions = [];
      let options;
      options = {
        name: "",
        category_id: ""
      };
      pointsNews.getCategory(options).then(function(res) {
        let data = res.data;
        if (res.code == 1) {
          for (let i = 0; i < data.length; i++) {
            _this.categoryOptions.push({
              value: data[i].category_id,
              label: data[i].name
            });
          }
        }
      });
    },
    //获取项目
    getProject() {
      let _this = this;
      this.projectOptions = [];
      let options;
      options = {
        spid: "",
        topic: ""
      };
      pointsNews.getProject(options).then(function(res) {
        let data = res.data;
        if (res.code == 1) {
          for (let i = 0; i < data.models.length; i++) {
            _this.projectOptions.push({
              value: data.models[i].id,
              label: data.models[i].topic
            });
          }
        }
      });
    },
    //上传图片成功
    uploadImgSuccess(response, file, fileList) {
      this.newImgUrl = fileList;
    },
    //删除图片
    handleRemove(file, fileList) {
      this.newImgUrl = fileList;
    },
    //预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //返回
    goBack() {
      history.go(-1);
    },
    //  获取地址栏参数
    getUrlKey(name) {
      return (
        decodeURIComponent(
          (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
            location.href
          ) || [, ""])[1].replace(/\+/g, "%20")
        ) || null
      );
    },
    //错误弹窗
    messageAlert(msg) {
      this.$message.error(msg);
    },
    //成功弹窗
    successfulAlert(msg) {
      this.$message({
        message: msg,
        type: "success"
      });
    }
  }
};
</script>

<style lang="less">
.topEdit {
  height: 80px;
  padding: 20px;
  li {
    float: left;
    margin-right: 30px;
    span {
      float: left;
      line-height: 38px;
      color: #f56c6c;
    }
    .el-input {
      float: left;
      width: 200px;
    }
  }
}
.editItem {
  padding: 20px 20px;
  .group1 {
    .leftTitle {
      float: left;
      height: 36px;
      line-height: 36px;
      font-size: 14px;
      color: #2d2d2d;
      min-width: 60px;
      margin-right: 10px;
    }
    .rightContent {
      float: left;
      .tip1 {
        float: left;
        color: #999;
        font-size: 12px;
      }
    }
    .lgRightContent {
      width: 40%;
    }
  }
}
.operationButtom {
  text-align: center;
  height: 100px;
  margin-top: 30px;
}
</style>
